package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author sxnan
 * @className StaticResourceUtil
 * @description TODO
 * @date 2020/7/21
 */
public class StaticResourceUtil {

    /**
     * 根据url路径获取静态资源文件的真实路径
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path){
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        return absolutePath.replaceAll("\\\\","/")+path;
    }

    /**
     * 读取静态资源文件输入流，通过输出流输出
     * @param inputStream
     * @param outputStream
     */
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int count = 0;//count不为零的时候就是读取到文件输入流中内容的时候
        while(count==0){
            count = inputStream.available();
        }
        int resourceSize = count;
        //先输出http请求头，在输出具体的内容
        outputStream.write(HttpProtocolUtil.getHeaderStr200(resourceSize).getBytes());

        /**
         * 处理输出具体内容
         * 当读取的文件流有可能非常大的时候，可以使用多次输出的方式
         */
        int writen = 0;//已经读取的文件长度
        int byteSize = 1024;//计划每次读取的文件长度
        byte[] bytes = new byte[byteSize];
        while(writen<resourceSize){
            if (resourceSize<writen+byteSize){
                byteSize = resourceSize - writen;
                bytes = new byte[byteSize];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();
            writen+=byteSize;
        }

    }
}
